package cn.com.infcn.monitor.task.sql;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.visitor.SchemaStatVisitor;
import com.alibaba.druid.stat.DruidStatManagerFacade;

import cn.com.infcn.monitor.task.BaseTask;

public class SqlDetailTask implements BaseTask {
	
	private static DruidStatManagerFacade statManagerFacade = DruidStatManagerFacade.getInstance();

	private Integer id;
	
	public SqlDetailTask(Integer id) {
		this.id = id;
	}

	@Override
	public Object execute() throws Exception {
		return httpRequest();
	}

	public Object httpRequest() {
		try {
			Map<String, Object> map = statManagerFacade.getSqlStatData(id);

	        if (map == null) {
	            return null;
	        }

	        String dbType = (String) map.get("DbType");
	        String sql = (String) map.get("SQL");

	        map.put("formattedSql", SQLUtils.format(sql, dbType));
	        List<SQLStatement> statementList = SQLUtils.parseStatements(sql, dbType);

	        if (!statementList.isEmpty()) {
	            SQLStatement statemen = statementList.get(0);
	            SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(statementList, dbType);
	            statemen.accept(visitor);
	            map.put("parsedTable", visitor.getTables().toString());
	            map.put("parsedFields", visitor.getColumns().toString());
	            map.put("parsedConditions", visitor.getConditions().toString());
	            map.put("parsedRelationships", visitor.getRelationships().toString());
	            map.put("parsedOrderbycolumns", visitor.getOrderByColumns().toString());
	        }

	        DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
	        Date maxTimespanOccurTime = (Date) map.get("MaxTimespanOccurTime");
	        if (maxTimespanOccurTime != null) {
	            map.put("MaxTimespanOccurTime", format.format(maxTimespanOccurTime));
	        }

	        return map;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
